<template>
  <div
    class="test-account-container animate__faster animate__animated animate__fadeIn"
  >
    <!-- 顶部条件筛选 -->
    <div class="screen-conditions-container">
      <ScreenConditions :isDataType="false">
        <template slot="conditions">
          <AssociativeSelectGroup
            :map="selectMap"
            v-model="defaultTime"
            :activeDate="activeDate"
            @conditionChange="selectGroupChange($event)"
          >
            <template slot="space_1">
              <topSelect ref="selectChild" :trialNum="parentNum"></topSelect>
            </template>
          </AssociativeSelectGroup>
        </template>
        <template slot="operate">
          <a-button type="primary" @click="getTableData()"> 查询 </a-button>
        </template>
      </ScreenConditions>
    </div>
    <div
      class="test-account-body animate__faster animate__animated animate__fadeIn"
      v-loading="loading"
    >
      <div class="data-report-body">
        <div
          class="test-menu"
          :class="{ 'animate-in': isOpen, 'animate-out': !isOpen }"
        >
          <div class="zhgd-data-report-header" header="试验项目"></div>
          <div class="video-menu-tree">
            <a-empty v-if="treeData.length == 0" />
            <a-tree
              v-else
              blockNode
              show-icon
              v-model="checkedKeys"
              :expanded-keys="expandedKeys"
              :auto-expand-parent="autoExpandParent"
              :selected-keys="selectedKeys"
              :tree-data="treeData"
              :replaceFields="{
                children: 'children',
                title: 'trialName',
                key: 'trialNum',
              }"
              @expand="onExpand"
              @select="onSelect"
            >
              <template slot="custom" slot-scope="{ children }">
                <img
                  v-if="children && children.length > 0"
                  class="menu-icon"
                  src="https://jszhgd.cn/static/pc/folder.png"
                />
                <img
                  v-else
                  class="menu-icon"
                  src="https://jszhgd.cn/static/pc/file.png"
                />
              </template>
            </a-tree>
          </div>
          <img
            class="arrow"
            :src="
              isOpen
                ? 'https://jszhgd.cn/static/pc/trial/close.png'
                : 'https://jszhgd.cn/static/pc/trial/open.png'
            "
            alt=""
            @click="isOpen = !isOpen"
          />
        </div>
        <div class="table-body">
          <a-empty v-if="chartList.length == 0"></a-empty>
          <div v-else>
            <div class="chart-wrap" v-for="(v, i) in chartList" :key="i">
              <div class="chart-title">
                <span class="text"> {{ v.text }}</span>
                <span class="unit">（{{ v.unit }}）</span>
              </div>
              <a-empty v-if="v.xlist.length == 0"></a-empty>
              <div v-else class="chart-body" :ref="'chart_dom_' + i"></div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
const { assets_host } = require("@/environment/index.js");
import AssociativeSelectGroup from "@/components/wisdom-beam/trial-app/AssociativeSelectGroup";
import bjIcon from "@/components/bj-icon";
import topSelect from "../testAccount/components/select";
import {
  notificationTip,
  addAttributeByKey,
  getNodeByKey,
  deepMerge,
  flatTreeData,
} from "@/utils";
import charMixins from "@/mixins/echarts";
import themeColors from "@/theme/compileFiles/cssVaribles.less";
import {
  recordListByTenantCode,
  chartList,
  getTestHasDataDate,
} from "@/api/wisdom-beam/trial-app";
export default {
  mixins: [charMixins],
  components: {
    AssociativeSelectGroup,
    topSelect,
    bjIcon,
  },
  data() {
    return {
      assets_host: assets_host,
      loading: false,
      activeDate: [],
      selectMap: [
        {
          type: "calendar",
        },
      ],
      conditionsData: {},
      select: {
        precativeNum: "",
        reportNum: "",
        sampleNum: "",
      },
      defaultTime: [],
      tableData: [],
      pager: {
        page: 1,
        pageSize: 10,
        total: 0,
      },

      isOpen: true, //默认展开
      expandedKeys: [],
      autoExpandParent: true,
      checkedKeys: [],
      selectedKeys: [],
      treeData: [],

      trialNum: "",
      parentNum: "",
      lqType: "", //沥青名称

      chartList: [],
      color: [
        themeColors["--echart-pale-red"],
        themeColors["--echart-green"],
        themeColors["--echart-purple"],
        themeColors["--echart-blue"],
        themeColors["--echart-yellow"],
        themeColors["--echart-light-blue"],
        themeColors["--echart-pink"],
        themeColors["--echart-orange"],
      ],
    };
  },
  mounted() {
    this.getNodeTreeList();
  },
  methods: {
    //初始化统计图
    initLineChar(refs, opt = {}) {
      let { legendList, ylist, xlist, downList, upList } = opt;
      let series = [];
      ylist.forEach((v, i) => {
        let arr = [];
        ylist[i].forEach((item) => {
          arr.push([
            item.date,
            item.testValue,
            item.result,
            item.standardValue,
          ]);
        });
        series.push({
          name: legendList[i],
          type: "scatter",
          data: arr,
        });
      });
      series.push(
        {
          type: "line",
          data: downList,
          itemStyle: {
            color: "#ff1616",
          },
          lineStyle: {
            color: "#ff1616",
            width: 2,
            type: "dashed",
          },
          //   symbol: "none",
        },
        {
          type: "line",
          data: upList,
          itemStyle: {
            color: "#ff1616",
          },
          lineStyle: {
            color: "#ff1616",
            width: 2,
            type: "dashed",
          },
          //   symbol: "none",
        }
      );
      let chart_dom = this.$refs[refs];
      try {
        let chartInstance = this.$echarts.init(chart_dom[0]);
        let baseOptions = {};
        let tooltip = {
          trigger: "item",
          formatter: (params) => {
            if (params.componentSubType == "line") return "";
            else {
              let result = params.value[2];
              let resultStr = "";
              if (result == 0) {
                resultStr = "合格";
              } else if (result == 1) {
                resultStr = "不合格";
              } else if (result == 2) {
                resultStr = "试验数据无效";
              } else if (result == -1) {
                resultStr = "实测";
              }
              return `
                <div>试验时间：${params.name}</div>
                <div>代表值：${params.value[1]}</div>
                <div>试验结果：${resultStr}</div>
                <div>技术指标：${params.value[3]}</div>`;
            }
          },
        };
        baseOptions = {
          legend: {
            data: legendList,
          },
          color: this.color,
          grid: {
            top: "100px",
            left: "80px",
            right: "60px",
            bottom: "80px",
          },
          tooltip: tooltip,
          xAxis: {
            type: "category",
            data: xlist,
          },
          yAxis: {
            type: "value",
          },
          dataZoom: [
            {
              type: "inside",
              start: 0,
              end: 100,
            },
            {
              start: 0,
              end: 100,
              height: 20,
              fillerColor: "rgba(167,183,204,0.4)",
              handleIcon:
                "M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4v1.3h1.3v-1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z",
              handleSize: "80%",
              handleStyle: {
                color: "#fff",
                borderColor: "rgba(0, 0, 0, 0.2)",
                shadowBlur: 3,
                shadowColor: "rgba(0, 0, 0, 0.6)",
                shadowOffsetX: 2,
                shadowOffsetY: 2,
              },
            },
          ],
          series: series,
        };
        chartInstance.setOption(deepMerge(this.lineChartsOptions, baseOptions));
        //开启响应式
        window.addEventListener("resize", () => {
          chartInstance.resize();
        });
      } catch (err) {}
    },

    //查询有数据的日期列表
    getDateList() {
      let {
        conditionsData: { block },
        defaultTime,
      } = this;
      let {
        selectData: { result, dataSource },
        form: {
          strengthGrade,
          curingAge,
          kind,
          brand,
          nominalDiameter,
          lqType,
          asphaltNum,
          asphaltLevel,
          weatherRegion,
          temperature,
          mxeType,
          roadLevel,
          trafficType,
          designStrength,
          surface,
        },
      } = this.$refs.selectChild;
      getTestHasDataDate({
        orgCode: block,
        category: this.trialNum, //试验类别
        strengthGrade: strengthGrade || "",
        curingAge: curingAge || "",
        kind: kind || "",
        brand: brand || "",
        nominalDiameter: nominalDiameter || "",
        lqType: "",
        asphaltNum: asphaltNum || "",
        asphaltLevel: asphaltLevel || "",
        weatherRegion: weatherRegion || "",
        temperature: temperature || "",
        mxeType: mxeType || "",
        roadLevel: roadLevel || "",
        trafficType: trafficType || "",
        designStrength: designStrength || "",
        surface: surface || "",
        result: result,
        dataSource: dataSource,
        startTime: defaultTime[0] || "",
        endTime: defaultTime[1] || "",
      })
        .then((res) => {
          let { data } = res;
          this.activeDate = data.result || [];
        })
        .catch((_) => {
          this.activeDate = [];
        });
    },

    getTableData(trialNum = this.trialNum) {
      this.getDateList();
      let {
        conditionsData: { block },
        defaultTime,
      } = this;
      let {
        selectData: { result, dataSource },
        form: {
          strengthGrade,
          curingAge,
          kind,
          brand,
          nominalDiameter,
          lqType,
          asphaltNum,
          asphaltLevel,
          weatherRegion,
          temperature,
          mxeType,
          roadLevel,
          trafficType,
          designStrength,
          surface,
        },
      } = this.$refs.selectChild;
      chartList({
        orgCode: block,
        category: trialNum, //试验类别
        strengthGrade: strengthGrade || "",
        curingAge: curingAge || "",
        kind: kind || "",
        brand: brand || "",
        nominalDiameter: nominalDiameter || "",
        lqType: "",
        asphaltNum: asphaltNum || "",
        asphaltLevel: asphaltLevel || "",
        weatherRegion: weatherRegion || "",
        temperature: temperature || "",
        mxeType: mxeType || "",
        roadLevel: roadLevel || "",
        trafficType: trafficType || "",
        designStrength: designStrength || "",
        surface: surface || "",
        result: result,
        dataSource: dataSource,
        startTime: defaultTime[0] || "",
        endTime: defaultTime[1] || "",
      })
        .then((res) => {
          let {
            data: { result },
          } = res;
          this.chartList = result || [];
          this.$nextTick((_) => {
            this.chartList.forEach((item, index) => {
              this.initLineChar("chart_dom_" + index, item);
            });
          });
        })
        .catch((_) => {});
    },

    //获取根节点树数据
    getNodeTreeList() {
      recordListByTenantCode()
        .then((res) => {
          let filterData = addAttributeByKey(
            null,
            "scopedSlots",
            { icon: "custom" },
            res.data.result,
            "children"
          );
          this.treeData = filterData;
          let firstNode = flatTreeData(filterData, "children").find(
            (v) => !v.children || v.children.length == 0
          );
          if (firstNode) {
            let { trialNum } = firstNode;
            this.trialNum = trialNum;
            this.getTableData(firstNode.trialNum);
            let selectItem = getNodeByKey(
              trialNum,
              "trialNum",
              this.treeData,
              "children"
            );
            this.parentNum = selectItem.parentNum || "";
            this.checkedKeys = [trialNum];
            this.selectedKeys = [trialNum];
            this.expandedKeys = [trialNum];
          } else {
            this.checkedKeys = [];
            this.selectedKeys = [];
          }
        })
        .catch();
    },
    // 查找一个树多有第一个节点，深度遍历
    getFirstNode(tree) {
      var temp = [];
      var forFn = function (arr) {
        if (arr && arr.length > 0) {
          temp.push(arr[0]);
          if (arr[0].children) {
            forFn(arr[0].children);
          }
        }
      };
      forFn(tree);
      return temp;
    },

    onExpand(expandedKeys) {
      this.expandedKeys = expandedKeys;
      this.autoExpandParent = false;
    },
    //树选择事件
    onSelect(selectedKeys, { node }) {
      node.onExpand();
      this.selectedKeys = selectedKeys;
      this.trialNum = selectedKeys[0];
      let selectItem = getNodeByKey(
        this.trialNum,
        "trialNum",
        this.treeData,
        "children"
      );
      this.lqType = selectItem?.lqType || "";
      if (
        selectItem &&
        (selectItem.children == null || selectItem.children.length == 0)
      ) {
        this.parentNum = selectItem.parentNum || "";
        this.getTableData(selectItem.trialNum);
      }
    },
    //删除
    handleDelClick(row) {
      let that = this;
      let { id } = row;
      const h = this.$createElement;
      this.$confirm({
        title: "您确定删除所选内容?",
        content: "删除内容后,将无法恢复。",
        okText: "确定",
        okType: "primary",
        cancelText: "取消",
        centered: true,
        icon: () =>
          h("a-icon", {
            props: {
              type: "question-circle",
              theme: "filled",
            },
            style: "color:#FB5A5A",
          }),
        onOk() {
          return new Promise((resolve, reject) => {
            deleteReport(id)
              .then((res) => {
                notificationTip("success", "删除成功!");
                that.getTableData();
                resolve();
              })
              .catch((_) => {
                reject();
                notificationTip("error", "删除失败!");
              });
          });
        },
        onCancel() {},
      });
    },

    selectGroupChange(data) {
      this.dealConditionsData(data);
      this.getTableData();
    },
    //处理搜索区域选中值
    dealConditionsData(data = {}) {
      Object.keys(data).forEach((key) => {
        if (!data[key]) {
          this.conditionsData[key] = "";
        } else if (Array.isArray(data[key])) {
          this.conditionsData[key] = data[key]
            .map((v) => v.key)
            .filter((v) => v)
            .toString();
        } else if (
          Object.prototype.toString.call(data[key]) === "[object Object]"
        ) {
          this.conditionsData[key] = data[key].key;
        } else {
          this.conditionsData[key] = "";
        }
      });
    },
  },
};
</script>

<style lang="less" scoped>
.test-account-container {
  padding: 0 0 10px 10px;
  height: 100%;
  .flex();
  flex-direction: column;
  .test-account-body {
    flex: 1;
    overflow: hidden;
    margin: 10px 10px 0 0;
    .data-report-body {
      width: 100%;
      height: 100%;
      .flex();
      .test-menu {
        width: 304px;
        height: 100%;
        background: #fff;
        padding: 0px 15px 20px;
        box-sizing: border-box;
        .flex();
        flex-direction: column;
        position: relative;
        transition: 0.8s;
        margin-right: 12px;
        .zhgd-data-report-header {
          padding: 12px 0;
          &::before {
            content: attr(header);
            height: 18px;
            display: flex;
            align-items: center;
            border-left: 3px solid var(--primary-color);
            padding-left: 10px;
            margin-bottom: 20px;
            font-size: 18px;
            font-weight: 400;
            color: #525a5d;
            position: relative;
            top: 10px;
          }
          .video-menu-icon {
            font-size: 22px;
            color: var(--primary-color);
            position: relative;
            top: 2px;
          }
        }
        .arrow {
          position: absolute;
          top: 50%;
          right: -8px;
          cursor: pointer;
        }
        &.animate-in {
          left: 0;
          width: 304px;
          padding: 0px 15px 20px;
        }
        &.animate-out {
          left: -12px;
          width: 0px;
          margin-right: 0;
          padding: 0 6px;
          /deep/.ant-tree li {
            padding-left: 12px;
          }
          .zhgd-data-report-header {
            &::before {
              padding-left: 20px;
            }
          }
        }
      }
      .table-body {
        flex: 1;
        background: #fff;
        margin-left: 2px;
        overflow: hidden;
        z-index: 99;
        .custom-scrollbar();
        .chart-wrap {
          height: 480px;
          position: relative;
          .chart-title {
            position: absolute;
            top: 27px;
            left: 20px;
            display: flex;
            align-items: center;
            .text {
              color: #525a5d;
              font-size: 18px;
              margin-left: 12px;
            }
            .unit {
              color: #999;
              font-size: 14px;
            }
            &::before {
              position: absolute;
              content: "";
              height: 16px;
              border-left: 3px solid var(--primary-color);
            }
          }
          .chart-body {
            position: absolute;
            width: 100%;
            height: 100%;
          }
        }
      }
    }
  }
}
</style>
